package com.windward.vii.service.qq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sun.jersey.api.client.ClientResponse;
import com.windward.vii.common.JsonResult;
import com.windward.vii.common.ResultCode;
import com.windward.vii.service.qq.bean.QQUserInfo;
import com.windward.vii.service.weixin.bean.WeixinAccessToken;
import com.windward.vii.utils.HttpRestClient;
import com.windward.vii.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * http://wiki.connect.qq.com/get_user_info
 */
@Component
public class QQAuthService {

    private static final Logger logger = LoggerFactory.getLogger(QQAuthService.class);

    private static final String APP_ID = "";
    private static final String APP_SECRET = "";

    // https://graph.qq.com/user/get_user_info?access_token=YOUR_ACCESS_TOKEN&oauth_consumer_key=YOUR_APP_ID&openid=YOUR_OPENID
    private static final String USER_INFO_URL = "https://graph.qq.com/user/get_user_info";

    public JsonResult getUserInfo(String access_token, String openid) {
        if(StringUtils.isBlank(access_token)) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "无效的access_token");
        }
        if(StringUtils.isBlank(openid)) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "无效的openid");
        }
        StringBuilder url = new StringBuilder();
        url.append(USER_INFO_URL).append("?access_token=").append(access_token)
                .append("&oauth_consumer_key=").append(APP_ID)
                .append("&openid=").append(openid);
        ClientResponse response = HttpRestClient.get(url.toString());
        if(response == null) {
            return new JsonResult(ResultCode.ERROR_CODE, "获取用户信息失败(response err)，请重试");
        }
        String content = response.getEntity(String.class);
        if(StringUtils.isBlank(content)) {
            return new JsonResult(ResultCode.ERROR_CODE, "获取用户信息失败(content err)，请重试");
        }
        logger.info("getUserInfo-response={}" + content);
        QQUserInfo userInfo = JSON.parseObject(content, QQUserInfo.class);
        if(userInfo == null) {
            return new JsonResult(ResultCode.ERROR_CODE, "获取用户信息失败(json err)，请重试");
        }
        JsonResult result = new JsonResult();
        if(userInfo.getRet() != 0) {
            result.setCode(userInfo.getRet());
            result.setMsg(userInfo.getMsg());
        } else {
            result.setCode(ResultCode.SUCCESS_CODE);
            result.setMsg(ResultCode.SUCCESS_MSG);
            result.setBody(userInfo);
        }
        return result;
    }

}
